import React, { useState, useEffect } from 'react';
import { Table, Tag, Space, Spin, Typography } from 'antd';
import { TrophyOutlined, CrownOutlined, StarOutlined } from '@ant-design/icons';
import http from '@/http';
import { Contest } from '@/types/contest';
import styles from './ContestRanking.module.css';

const { Text } = Typography;

interface ContestRankingProps {
  contest: Contest;
}

interface RankingItem {
  id: number;
  user: {
    id: number;
    username: string;
    email: string | null;
    admin_type: string;
    last_login: string | null;
  };
  profile: {
    id: number;
    username: string;
    email: string | null;
    admin_type: string;
    avatar: string;
    real_name: string;
    blog: string;
    mood: string;
    github: string;
    school: string;
    major: string;
    language: string;
    submission_number: number;
    accepted_number: number;
  };
  submission_number: number;
  accepted_number?: number;
  total_time?: number;
  total_score?: number;
  submission_info: {
    [key: string]: {
      is_ac: boolean;
      ac_time: number;
      error_number: number;
      is_first_ac: boolean;
    } | number;
  };
  contest: number;
}

interface RankingResponse {
  code: number;
  message: string;
  data: {
    count: number;
    next: string | null;
    previous: string | null;
    results: RankingItem[];
  };
  timestamp: string;
}

const ContestRanking: React.FC<ContestRankingProps> = ({ contest }) => {
  const [loading, setLoading] = useState(false);
  const [rankings, setRankings] = useState<RankingItem[]>([]);
  const [problemIds, setProblemIds] = useState<string[]>([]);

  useEffect(() => {
    if (contest?.id) {
      fetchRankings();
    }
  }, [contest?.id]);

  const fetchRankings = async () => {
    try {
      setLoading(true);
      const response = await http.get<RankingResponse>(`/api/contest/${contest.id}/rank/`);
      setRankings(response.data.data.results);
      
      // 从第一个参赛者的submission_info中获取所有题目ID
      if (response.data.data.results.length > 0) {
        const problemIds = Object.keys(response.data.data.results[0].submission_info);
        setProblemIds(problemIds);
      }
    } catch (error) {
      console.error('获取排行榜失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const renderRankIcon = (rank: number) => {
    switch (rank) {
      case 1:
        return <CrownOutlined style={{ color: '#FFD700', fontSize: '20px' }} />;
      case 2:
        return <CrownOutlined style={{ color: '#C0C0C0', fontSize: '20px' }} />;
      case 3:
        return <CrownOutlined style={{ color: '#CD7F32', fontSize: '20px' }} />;
      default:
        return rank;
    }
  };

  const renderProblemColumn = (problemId: string) => {
    return {
      title: `题目 ${problemId}`,
      dataIndex: ['submission_info', problemId],
      key: `problem_${problemId}`,
      render: (info: any, record: RankingItem) => {
        if (contest.rule_type === 'ACM') {
          const acInfo = info as { is_ac: boolean; ac_time: number; error_number: number };
          if (!acInfo) return null;
          
          return (
            <div>
              {acInfo.is_ac ? (
                <div>
                  <Tag color="green">AC</Tag>
                  <div>{Math.floor(acInfo.ac_time / 60)}分钟</div>
                  {acInfo.error_number > 0 && (
                    <div>(-{acInfo.error_number})</div>
                  )}
                </div>
              ) : (
                <div>
                  {acInfo.error_number > 0 && (
                    <Tag color="red">-{acInfo.error_number}</Tag>
                  )}
                </div>
              )}
            </div>
          );
        } else {
          const score = info as number;
          return (
            <div>
              <Tag color={score > 0 ? 'green' : 'default'}>
                {score}
              </Tag>
            </div>
          );
        }
      },
    };
  };

  const columns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      width: 80,
      render: (text: string, record: any, index: number) => renderRankIcon(index + 1),
    },
    {
      title: '用户名',
      key: 'username',
      render: (record: RankingItem) => (
        <Space>
          <Text>{record.user.username}</Text>
          {record.profile.real_name && (
            <Text type="secondary">({record.profile.real_name})</Text>
          )}
        </Space>
      ),
    },
    {
      title: '学校',
      dataIndex: ['profile', 'school'],
      key: 'school',
    },
    {
      title: contest.rule_type === 'ACM' ? '总用时' : '总分',
      key: 'score',
      render: (record: RankingItem) => (
        <div>
          {contest.rule_type === 'ACM' ? (
            <div>
              <Tag color="blue">{record.accepted_number}题</Tag>
              <div>{Math.floor((record.total_time || 0) / 60)}分钟</div>
            </div>
          ) : (
            <Tag color="blue">{record.total_score}</Tag>
          )}
        </div>
      ),
    },
    ...problemIds.map(problemId => renderProblemColumn(problemId)),
  ];

  return (
    <div className={styles.container}>
      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={rankings.map((item, index) => ({ ...item, rank: index + 1 }))}
          rowKey="id"
          pagination={false}
        />
      </Spin>
    </div>
  );
};

export default ContestRanking; 